package com.chcit.mobile.mvp.presenter;

import android.app.Application;

import com.chcit.mobile.app.utils.SharedPreUtils;
import com.chcit.mobile.mvp.model.entity.User;
import com.elvishew.xlog.XLog;
import com.jess.arms.base.app.ConfigKeys;
import com.jess.arms.base.app.Quick;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.chcit.mobile.mvp.contract.ServerContract;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.List;


@FragmentScope
public class ServerPresenter extends BasePresenter<ServerContract.Model, ServerContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public ServerPresenter(ServerContract.Model model, ServerContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void testAndSave(String url) {

        RetrofitUrlManager.getInstance().setGlobalDomain(url);
        mModel.test().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mRootView.showLoading();
                    }

                    @Override
                    public void onNext(String s) {
                        SharedPreUtils.getInstance().putString(ConfigKeys.API_HOST.name(), url);
                        mRootView.toLoginPage();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mRootView.showMessage(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
